<extend name="Public/base" />
<block name="content">
<link rel="stylesheet" type="text/css" href="__STATIC__/webuploader/css/webuploader.css" />
<link rel="stylesheet" type="text/css" href="__STATIC__/webuploader/css/style.css" />
<style>
#header{margin-top:0px;}
</style>
<div id="content">
	<div id="content-header">
		<div id="breadcrumb">
			<a class="tip-bottom" href="{:U('Index/index')}" data-original-title="首页"><i class="icon-home"></i> 首页</a>
			<a class="tip-bottom" href="{:U('Activity/index')}" data-original-title="">活动管理</a> <a class="current" href="{$post_url}">{$meta_title}</a>
		</div>
	</div>
	<div class="container-fluid"><hr>
    <div class="row-fluid">
      <div class="span12">
        <div class="widget-box">
          <div class="widget-title"> <span class="icon"> <i class="icon-briefcase"></i> </span>
            <h5>活动信息审核</h5>
            <span style="float:right;">
            	<button class="btn btn-success window-jump" url="{:U('activityJoinMember?activity_id='.$list['activity_id'])}">查看报名信息</button>
            	<button class="btn btn-success" href="#preview"  id="preview_button" data-toggle="modal" >预览</button>
            	<button class="btn btn-warning ajax-post" id="update">修改</button>
            	<button class="btn btn-info window-jump" url="{:U('activityTheme?activity_id='.$list['activity_id'])}">模板管理</button>
            	<button class="btn btn-info window-jump" url="{:U('activityThemeModule?activity_id='.$list['activity_id'])}">模块管理</button>
            	<switch name="list.marking_status">
				    <case value="-1">
				    {/*  活动审批下线 */}
				    	<button class="confirm btn btn-danger ajax-get"  href="{:U('activityMarkingStatus?method=go&id='.$list['activity_id'].'&marking_status=3')}">上线</button>
				    </case>
				    <case value="0">
				    {// 活动未审批 }
				   		<button class="btn btn-info ajax-get" href="{:U('activityMarkingStatus?method=pass&id='.$list['activity_id'].'&marking_status=2')}">通过 </button>
				   		<button class="btn btn-inverse ajax-get" href="{:U('activityMarkingStatus?method=refuse&id='.$list['activity_id'].'&marking_status=1')}">不通过</button>
				    </case> 
				    <case value="1">
				    {// 活动审批未通过 }
				    	<button class="btn btn-info ajax-get" href="{:U('activityMarkingStatus?method=pass&id='.$list['activity_id'].'&marking_status=2')}">通过 </button>
				    </case> 
				    <case value="2">
				  	  {// 活动审批通过 }
				    	<button class="confirm btn btn-danger ajax-get"  href="{:U('activityMarkingStatus?method=go&id='.$list['activity_id'].'&marking_status=3')}">上线</button>
				    </case>   
				    <case value="3">
				    {// 活动正式上线 }
				    	<button class="confirm btn btn-danger ajax-get"  href="{:U('activityMarkingStatus?method=coil&id='.$list['activity_id'].'&marking_status=-1')}">下线</button>
				    </case> 
				    <default />default
				</switch>
          	</span>
          </div>
          <div class="widget-content">
            <div class="row-fluid">
	              <div class="span12" style="margin-bottom:15px;">
	                <table>
	                  <tbody>
	                    <tr>
	                      <td><h3>{$list.activity_name|htmlspecialchars}</h3></td>
	                    </tr>
	                    <volist name="log_list" id="vo">
		                    <tr>
		                      <td>
			                      <span class="label">{$vo.create_time|time_format}&nbsp;&nbsp;&nbsp;&nbsp;{$vo.login_name}&nbsp;&nbsp;&nbsp;{$vo.log_type_text}"{$list.activity_name|htmlspecialchars}"。</span>
		                      </td>
		                    </tr>
	                 	 </volist>
	                  </tbody>
	                </table>
	              </div>
            <div class="row-fluid" >
	              <div class="span12">
	                <table class="table table-bordered table-invoice">
	                  <tbody>
	                    <tr>
	                      <td>活动名称:</td>
	                      <td><strong>{$list.activity_name|htmlspecialchars}</strong></td>
	                      <td>开始时间:</td>
	                      <td><strong>{$list.start_time|time_format}</strong></td>
	                    </tr>
	                    <tr>
	                      <td>活动类型:</td>
	                      <td><strong>{$list.activity_category_id|getActivityCategoryName}</strong></td>
	                       <td>结束时间:</td>
	                      <td><strong>{$list.end_time|time_format}</strong></td>
	                    </tr>
	                    <tr>
	                      <td>创建人:</td>
	                      <td><strong>{$list.create_user_id|getUserName}</strong></td>
	                       <td>预计报名人数:</td>
	                      <td><strong>{$list.expect_member_num|default='0'}</strong></td>
	                    </tr>
	                    <tr>
		                  	<td>活动创建时间:</td>
		                    <td><strong>{$list.create_time|time_format}</strong></td>
		                    <td>预计收入:</td>
		                    <td><strong>{$list.expect_money|default='0'}</strong></td>
	                 	</tr>
	                 	 <tr>
	                      <td>实际报名人数:</td>
	                      <td><strong>{$list.real_join_member_num|default='0'}</strong></td>
	                      <td>实际收入:</td>
	                      <td><strong>{$list.real_money|default='0'}</strong></td>
	                    </tr>
	                     <tr>
	                      <td colspan="2">实际到场人数:</td>
	                      <td colspan="2"><strong>{$list.real_member_num|default='0'}</strong></td>
	                    </tr>
	                  </tbody>
	                </table>
	              </div>
              </div>
            <div class="row_fluid">
              <!-- 活动下线后才会显示具体的实际信息 -->
              	<if condition=" $list.show_end_time lt NOW_TIME">
	              	<!-- 详细信息修改表单 -->
	             	 <form class="form-horizontal" method="post" action="" id="census">
						<div class="control-group">
							<label class="control-label">实际到场人数 :</label>
							<div class="controls">
								<input type="text" placeholder="实际到场人数" class="ui-wizard-content span2" name="real_member_num" value="{$list.real_member_num}" onkeyup="value=value.replace(/[a-zA-z]+$/,'')" >
							</div>
						</div>
						<div class="control-group">
							<label class="control-label">实际报名人数:</label>
							<div class="controls">
								<input type="text" placeholder="实际报名人数" class="ui-wizard-content span2" name="real_join_member_num" value="{$list.real_join_member_num}" onkeyup="value=value.replace(/[a-zA-z]+$/,'')">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label">实际收入:</label>
							<div class="controls">
								<input type="text" placeholder="实际收入" class="ui-wizard-content span2" name="real_money" value="{$list.real_money}" onkeyup="value=value.replace(/[a-zA-z]+$/,'')">
								<button class="btn btn-success" type="submit">提交</button>
							</div>
						</div>
						<input type="hidden" name="activity_id" value="{$list.activity_id}"/>
					</form>
					<!-- 表单结束 -->
				</if>
              </div>
              <!-- 相册 -->
            <div class="row-fluid">
			      <div class="span12">
			        <div class="widget-box">
			          <div class="widget-title"> <span class="icon"> <i class="icon-picture"></i> </span>
			            <h5>往期回顾图片</h5>
			          </div>
			          <div class="widget-content">
			            <ul class="thumbnails">
				            <volist name="pic_list" id="pic">
				              <li class="span1 pic_{$pic.pic_id}"> 
				              	<a> <img src="__ROOT__.{:getThumb($pic['path'],150,80)}" alt="" > </a>
				                <div class="actions"> 
				                	<a title="" href="javascript:void(0);"  class="delPic" activity_id="{$pic.activity_id}" pic_id="{$pic.pic_id}"><i class="icon-remove"></i></a> 
				                	<a class="lightbox_trigger" href="__ROOT__.{:getThumb($pic['path'],500,500)}"><i class="icon-search"></i></a> 
				                </div>
				              </li>
			           		</volist>
			            </ul>
			          </div>
			        </div>
			      </div>
			    </div>
            <!-- 相册结束 -->
            <!-- 上传图片 -->
            <div class="row_fluid">
					<div class="span12">
						<div class="widget-box">
							<div class="widget-title"> <span class="icon"> <i class="icon-picture"></i> </span>
								<h5>往期回顾图片</h5>
							</div>
							<div class="widget-content">
								<div class="control-group">
									<input type="hidden" name="pic_list" id="pic_list" value="{$list.pic_list|default=''}">
									<div class="controls">
										<div id="wrapper">
									       <div id="container" class="">
									        <!--头部，相册选择和格式选择-->
										         <div id="uploader">
									                <div class="queueList">
									                    <div id="dndArea" class="placeholder">
									                        <div id="filePicker"></div>
									                        <p>或将照片拖到这里，单次最多可选300张</p>
									                    </div>
									                </div>
									                <div class="statusBar" style="display:none;">
									                    <div class="progress">
									                        <span class="text">0%</span>
									                        <span class="percentage"></span>
									                    </div><div class="info"></div>
									                    <div class="btns">
									                        <div id="filePicker2"></div><div class="uploadBtn">开始上传</div>
									                    </div>
									                </div>
									            </div>
									        </div>
									    </div>
									</div>
								</div>
							</div>
						</div>
					</div>
            	</div>
            <!-- 上传图片结束 -->
          	</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 预览框 -->
<div id="preview" class="modal hide">
	<div class="modal-header">
		<button data-dismiss="modal" class="close" type="button">×</button>
		<h3>{$list.activity_name|htmlspecialchars}--模板列表</h3>
	</div>
	<div class="modal-body">
		 <notempty name="theme_list">
		 	<form action="{:U('Activity/activityLook')}" method="post" target="_blank" id="preview_form">
			 	<!-- 模板 -->
			 	<button class="btn btn-success" type="submit" >查看</button>
			 	<input type="hidden" name="id" value="{$list.activity_id}">
				<volist name="theme_list" id="list" >
					<dl class="cate-item">
						<dt class="cf">
							<div class="control-group">
								<label class="control-label">模板名称:</label>
								<div class="controls">
									<label>
										<input type="checkbox" name="theme_id" value="{$list.theme_id}" class="theme js_theme" check-class="theme" />{$list.theme_name}
					                </label>
								</div>
				            </div>
						</dt>
					</dl>
					<notempty name="list['data']">
						<dd>
							<!-- 位置 -->
							<volist name="list['data']" id="position">
								<div class="control-group">
									<label class="control-label">模块位置:{$position['position']}</label>
									<notempty name="position['module_list']">
										<volist name="position['module_list']" id="module">
											<div class="controls">
												<label>
													<input type="checkbox" name="module_id[{$list.theme_id}][{$position['position']}][]" value="{$module.module_id}" check-class="position_{$list.theme_id}_{$position['position']}" class="jsmodule" theme_id="{$list.theme_id}"/>{$module.module_name}
								                </label>
											</div>
								         </volist>
									</notempty>
								</div>
							</volist>
						</dd>
					</notempty>
					<hr/>
				</volist>
			</form>
			<else/>
				<dl class="cate-item">
					<dt class="cf">
						<div class="empty-div"> Oh~亲爱滴,暂时还没有内容!</div>
					</dt>
				</dl>
		</notempty>
	</div>
</div>

<script type="text/javascript">
$(document).ready(function(){
	$('.theme').on('change',function(){
	//	console.log($('input:radio[name=module_id]').val());
	//	$('#preview_form input:radio[name=module_id]').not('input:radio[name=module_id[4]]').removeAttr("checked");
		
	});
	//获取唯一的需要check的对象
	var check_collection = new Array();
	$('input[check-class]').each(function(){
		check_collection[$(this).attr('check-class')] = 1;
	});
	for(var key in check_collection){
		var check_selector = 'input[check-class='+key+']';
	//	console.log(check_selector);
		$(check_selector).attr('check-selector',check_selector).click(function(){
			//此处checked检测必须是相反的，因为UI框架的check事件要先发生于检测
			if($(this).attr('checked') == "checked"){
				$($(this).attr('check-selector')).attr('checked',false).parent('.checked').removeClass('checked');
				$(this).attr('checked',"checked").parent('.checked').addClass('checked');
			}else{
				$(this).attr('checked',false).parent('.checked').removeClass('checked');
			}
		});
	}

	//选择模板，则自动删除其他的位置选项
	$('.js_theme').click(function(){
		var all_collection = $('input[check-selector]');
		var chren_collection = $(this).closest('.cate-item').next('dd').find('input').add($(this)[0]);
		for(var all_key = 0 ;all_key < all_collection.length ; all_key++){
			for(var chren_key = 0 ;chren_key < chren_collection.length ; chren_key++){
				if(chren_collection[chren_key] == all_collection[all_key]){
					all_collection.splice(all_key,1);
				}
			}
		}
	 	all_collection.attr('checked',false).parent('.checked').removeClass('checked');
	});
	$("#census").submit(function(){
		//锁定登录按钮
		$('button').attr('disabled',true);
		var self = $(this);
		$.post("{$post_url}", self.serialize(), call_back, "json");
		return false;
		
		/**
		 * @todo 接收登录返回值
		 * @author PHP@妖孽 <dino_ma@163.com>
		 */
		function call_back(data){
			if(data.status==1){
				tke_alert(data.info,'alert-success');
				setTimeout(function(){
				  if (data.url) {
						location.href=data.url;
					}else{
						location.reload();
					}
				},1500);
			} else {
				$('button').attr('disabled',false);
				tke_alert(data.info,'alert-error');
			}
		}
	});
	//导航高亮
	highlight_subnav("{:U('Activity/index')}");
	//修改跳转
	$('#update').click(function(){
		window.location.href="{:U('edit',array('activity_id'=>(int)I('activity_id')))}";
	});
	//删除图片
	$('.delPic').click(function(){
		var activity_id = $.trim($(this).attr('activity_id'));
		var pic_id = $.trim($(this).attr('pic_id'));
		$.post("{:U('delActivityPic')}", {pic_id:pic_id,activity_id:activity_id}, function(data){
			if(data.status==1){
				//删除图片成功
				tke_alert(data.info,'alert-success');
				$('.pic_'+pic_id).hide();
			}else{
				tke_alert(data.info,'alert-error');
			}
			return false;
		}, "json");
	});
	//预览判断哦.~
	$('#preview_button').click(function(){
		//ajax获取数据
		/* window.location.href="{:U('activityLook',array('activity_id'=>(int)I('activity_id')))}"+"&theme_id="+activity_theme_id; */
	});
});
</script>

<!-- 百度上传 -->
<script type="text/javascript" src="__STATIC__/webuploader/js/webuploader.nolog.js"></script>
<script type="text/javascript">
(function( $ ){
    // 当domReady的时候开始初始化
    $(function() {
    	/**
    	 *@todo 上传活动图片
    	 */
    	function uploadPictureToActivity(pic_id){
    		var activity_id ="{:I('activity_id')}";
    		$.post("{:U('uploadActivityPicture')}", {pic_id:pic_id,activity_id:activity_id}, function(){
    			
    		}, "json");
    	}
    	
        var $wrap = $('#uploader'),

            // 图片容器
            $queue = $( '<ul class="filelist"></ul>' )
                .appendTo( $wrap.find( '.queueList' ) ),

            // 状态栏，包括进度和控制按钮
            $statusBar = $wrap.find( '.statusBar' ),

            // 文件总体选择信息。
            $info = $statusBar.find( '.info' ),

            // 上传按钮
            $upload = $wrap.find( '.uploadBtn' ),

            // 没选择文件之前的内容。
            $placeHolder = $wrap.find( '.placeholder' ),

            $progress = $statusBar.find( '.progress' ).hide(),

            // 添加的文件数量
            fileCount = 0,

            // 添加的文件总大小
            fileSize = 0,

            // 优化retina, 在retina下这个值是2
            ratio = window.devicePixelRatio || 1,

            // 缩略图大小
            thumbnailWidth = 110 * ratio,
            thumbnailHeight = 110 * ratio,

            // 可能有pedding, ready, uploading, confirm, done.
            state = 'pedding',

            // 所有文件的进度信息，key为file id
            percentages = {},
            // 判断浏览器是否支持图片的base64
            isSupportBase64 = ( function() {
                var data = new Image();
                var support = true;
                data.onload = data.onerror = function() {
                    if( this.width != 1 || this.height != 1 ) {
                        support = false;
                    }
                }
                data.src = "";
                return support;
            } )(),

            // 检测是否已经安装flash，检测flash的版本
            flashVersion = ( function() {
                var version;

                try {
                    version = navigator.plugins[ 'Shockwave Flash' ];
                    version = version.description;
                } catch ( ex ) {
                    try {
                        version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
                                .GetVariable('$version');
                    } catch ( ex2 ) {
                        version = '0.0';
                    }
                }
                version = version.match( /\d+/g );
                return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
            } )(),

            supportTransition = (function(){
                var s = document.createElement('p').style,
                    r = 'transition' in s ||
                            'WebkitTransition' in s ||
                            'MozTransition' in s ||
                            'msTransition' in s ||
                            'OTransition' in s;
                s = null;
                return r;
            })(),

            // WebUploader实例
            uploader;

        if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {

            // flash 安装了但是版本过低。
            if (flashVersion) {
                (function(container) {
                    window['expressinstallcallback'] = function( state ) {
                        switch(state) {
                            case 'Download.Cancelled':
                                alert('您取消了更新！')
                                break;

                            case 'Download.Failed':
                                alert('安装失败')
                                break;

                            default:
                                alert('安装已成功，请刷新！');
                                break;
                        }
                        delete window['expressinstallcallback'];
                    };

                    var swf = './expressInstall.swf';
                    // insert flash object
                    var html = '<object type="application/' +
                            'x-shockwave-flash" data="' +  swf + '" ';

                    if (WebUploader.browser.ie) {
                        html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                    }

                    html += 'width="100%" height="100%" style="outline:0">'  +
                        '<param name="movie" value="' + swf + '" />' +
                        '<param name="wmode" value="transparent" />' +
                        '<param name="allowscriptaccess" value="always" />' +
                    '</object>';

                    container.html(html);

                })($wrap);

            // 压根就没有安转。
            } else {
                $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
            }

            return;
        } else if (!WebUploader.Uploader.support()) {
            alert( 'Web Uploader 不支持您的浏览器！');
            return;
        }

        // 实例化
        uploader = WebUploader.create({
            pick: {
                id: '#filePicker',
                label: '点击选择图片'
            },
            formData: {
               
            },
            dnd: '#dndArea',
            paste: '#uploader',
            swf: "__STATIC__"+'/webuploader/js/Uploader.swf',
            chunked: false,
            chunkSize: 512 * 1024,
            server: '{:U("File/uploadPicture")}',
           //  runtimeOrder: 'flash',
				
              accept: {
                 title: 'Images',
                 extensions: 'jpg,jpeg,bmp,png',
                 mimeTypes: 'image/*'
             }, 
            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
            disableGlobalDnd: true,
            fileNumLimit: 300,
            fileSizeLimit: 200 * 1024 * 1024,    // 200 M
            fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
        });

        // 拖拽时不接受 js, txt 文件。
        uploader.on( 'dndAccept', function( items ) {
            var denied = false,
                len = items.length,
                i = 0,
                // 修改js类型
                unAllowed = 'text/plain;application/javascript ';

            for ( ; i < len; i++ ) {
                // 如果在列表里面
                if ( ~unAllowed.indexOf( items[ i ].type ) ) {
                    denied = true;
                    break;
                }
            }

            return !denied;
        });

        // uploader.on('filesQueued', function() {
        //     uploader.sort(function( a, b ) {
        //         if ( a.name < b.name )
        //           return -1;
        //         if ( a.name > b.name )
        //           return 1;
        //         return 0;
        //     });
        // });

        // 添加“添加文件”的按钮，
        uploader.addButton({
            id: '#filePicker2',
            label: '继续添加'
        });

        uploader.on('ready', function() {
            window.uploader = uploader;
        });
		//上传成功回调函数
        uploader.on('uploadSuccess',function(file,respone){
        	
        	uploadPictureToActivity(respone.data.id);
        //	$('#pic_id').val(respone.data.id);
        });
        // 当有文件添加进来时执行，负责view的创建
        function addFile( file ) {
            var $li = $( '<li id="' + file.id + '">' +
                    '<p class="title">' + file.name + '</p>' +
                    '<p class="imgWrap"></p>'+
                    '<p class="progress"><span></span></p>' +
                    '</li>' ),

                $btns = $('<div class="file-panel">' +
                    '<span class="cancel">删除</span>' +
                    '<span class="rotateRight">向右旋转</span>' +
                    '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find( 'p.imgWrap' ),
                $info = $('<p class="error"></p>'),

                showError = function( code ) {
                    switch( code ) {
                        case 'exceed_size':
                            text = '文件大小超出';
                            break;

                        case 'interrupt':
                            text = '上传暂停';
                            break;

                        default:
                            text = '上传失败，请重试';
                            break;
                    }

                    $info.text( text ).appendTo( $li );
                };

            if ( file.getStatus() === 'invalid' ) {
                showError( file.statusText );
            } else {
                // @todo lazyload
                $wrap.text( '预览中' );
                uploader.makeThumb( file, function( error, src ) {
                    var img;

                    if ( error ) {
                        $wrap.text( '不能预览' );
                        return;
                    }

                    if( isSupportBase64 ) {
                        img = $('<img src="'+src+'">');
                        $wrap.empty().append( img );
                    } else {
                        $.ajax('./preview.php', {
                            method: 'POST',
                            data: src,
                            dataType:'json'
                        }).done(function( response ) {
                            if (response.result) {
                                img = $('<img src="'+response.result+'">');
                                $wrap.empty().append( img );
                            } else {
                                $wrap.text("预览出错");
                            }
                        });
                    }
                }, thumbnailWidth, thumbnailHeight );

                percentages[ file.id ] = [ file.size, 0 ];
                file.rotation = 0;
            }

            file.on('statuschange', function( cur, prev ) {
                if ( prev === 'progress' ) {
                    $prgress.hide().width(0);
                } else if ( prev === 'queued' ) {
                    $li.off( 'mouseenter mouseleave' );
                    $btns.remove();
                }

                // 成功
                if ( cur === 'error' || cur === 'invalid' ) {
          //          console.log( file.statusText );
                    showError( file.statusText );
                    percentages[ file.id ][ 1 ] = 1;
                } else if ( cur === 'interrupt' ) {
                    showError( 'interrupt' );
                } else if ( cur === 'queued' ) {
                    percentages[ file.id ][ 1 ] = 0;
                } else if ( cur === 'progress' ) {
                    $info.remove();
                    $prgress.css('display', 'block');
                } else if ( cur === 'complete' ) {
                    $li.append( '<span class="success"></span>' );
                }

                $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
            });

            $li.on( 'mouseenter', function() {
                $btns.stop().animate({height: 30});
            });

            $li.on( 'mouseleave', function() {
                $btns.stop().animate({height: 0});
            });

            $btns.on( 'click', 'span', function() {
                var index = $(this).index(),
                    deg;

                switch ( index ) {
                    case 0:
                        uploader.removeFile( file );
                        return;

                    case 1:
                        file.rotation += 90;
                        break;

                    case 2:
                        file.rotation -= 90;
                        break;
                }

                if ( supportTransition ) {
                    deg = 'rotate(' + file.rotation + 'deg)';
                    $wrap.css({
                        '-webkit-transform': deg,
                        '-mos-transform': deg,
                        '-o-transform': deg,
                        'transform': deg
                    });
                } else {
                    $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
                    // use jquery animate to rotation
                    // $({
                    //     rotation: rotation
                    // }).animate({
                    //     rotation: file.rotation
                    // }, {
                    //     easing: 'linear',
                    //     step: function( now ) {
                    //         now = now * Math.PI / 180;

                    //         var cos = Math.cos( now ),
                    //             sin = Math.sin( now );

                    //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
                    //     }
                    // });
                }


            });

            $li.appendTo( $queue );
        }

        // 负责view的销毁
        function removeFile( file ) {
            var $li = $('#'+file.id);

            delete percentages[ file.id ];
            updateTotalProgress();
            $li.off().find('.file-panel').off().end().remove();
        }

        function updateTotalProgress() {
            var loaded = 0,
                total = 0,
                spans = $progress.children(),
                percent;

            $.each( percentages, function( k, v ) {
                total += v[ 0 ];
                loaded += v[ 0 ] * v[ 1 ];
            } );

            percent = total ? loaded / total : 0;


            spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
            spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
            updateStatus();
        }

        function updateStatus() {
            var text = '', stats;
            if ( state === 'ready' ) {
                text = '选中' + fileCount + '张图片，共' +
                        WebUploader.formatSize( fileSize ) + '。';
            } else if ( state === 'confirm' ) {
                stats = uploader.getStats();
                if ( stats.uploadFailNum ) {
                    text = '已成功上传' + stats.successNum+ '张照片，'+
                        stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                }

            } else {
                stats = uploader.getStats();
                text = '共' + fileCount + '张（' +
                        WebUploader.formatSize( fileSize )  +
                        '），已上传' + stats.successNum + '张';

                if ( stats.uploadFailNum ) {
                    text += '，失败' + stats.uploadFailNum + '张';
                }
            }

            $info.html( text );
        }

        function setState( val ) {
            var file, stats;
            if ( val === state ) {
                return;
            }

            $upload.removeClass( 'state-' + state );
            $upload.addClass( 'state-' + val );
            state = val;

            switch ( state ) {
                case 'pedding':
                    $placeHolder.removeClass( 'element-invisible' );
                    $queue.hide();
                    $statusBar.addClass( 'element-invisible' );
                    uploader.refresh();
                    break;

                case 'ready':
                    $placeHolder.addClass( 'element-invisible' );
                    $( '#filePicker2' ).removeClass( 'element-invisible');
                    $queue.show();
                    $statusBar.removeClass('element-invisible');
                    uploader.refresh();
                    break;

                case 'uploading':
                    $( '#filePicker2' ).addClass( 'element-invisible' );
                    $progress.show();
                    $upload.text( '暂停上传' );
                    break;

                case 'paused':
                    $progress.show();
                    $upload.text( '继续上传' );
                    break;

                case 'confirm':
                    $progress.hide();
                    $( '#filePicker2' ).removeClass( 'element-invisible' );
                    $upload.text( '开始上传' );

                    stats = uploader.getStats();
                    if ( stats.successNum && !stats.uploadFailNum ) {
                        setState( 'finish' );
                        return;
                    }
                    break;
                case 'finish':
                    stats = uploader.getStats();
                    if ( stats.successNum ) {
                        alert( '上传成功' );
                     	return false;
                    } else {
                        // 没有成功的图片，重设
                        state = 'done';
                        location.reload();
                    }
                    break;
            }

            updateStatus();
        }

        uploader.onUploadProgress = function( file, percentage ) {
            var $li = $('#'+file.id),
                $percent = $li.find('.progress span');

            $percent.css( 'width', percentage * 100 + '%' );
            percentages[ file.id ][ 1 ] = percentage;
            updateTotalProgress();
        };

        uploader.onFileQueued = function( file ) {
            fileCount++;
            fileSize += file.size;
            if ( fileCount === 1 ) {
                $placeHolder.addClass( 'element-invisible' );
                $statusBar.show();
            }

            addFile( file );
            setState( 'ready' );
            updateTotalProgress();
        };

        uploader.onFileDequeued = function( file ) {
            fileCount--;
            fileSize -= file.size;

            if ( !fileCount ) {
                setState( 'pedding' );
            }

            removeFile( file );
            updateTotalProgress();

        };

        uploader.on( 'all', function( type ) {
            var stats;
            switch( type ) {
                case 'uploadFinished':
                    setState( 'confirm' );
                    break;

                case 'startUpload':
                    setState( 'uploading' );
                    break;

                case 'stopUpload':
                    setState( 'paused' );
                    break;

            }
        });

        uploader.onError = function( code ) {
            alert( 'Eroor: ' + code );
        };

        $upload.on('click', function() {
            if ( $(this).hasClass( 'disabled' ) ) {
                return false;
            }

            if ( state === 'ready' ) {
                uploader.upload();
            } else if ( state === 'paused' ) {
                uploader.upload();
            } else if ( state === 'uploading' ) {
                uploader.stop();
            }
        });

        $info.on( 'click', '.retry', function() {
            uploader.retry();
        } );

        $info.on( 'click', '.ignore', function() {
            alert( 'todo' );
        } );

        $upload.addClass( 'state-' + state );
        updateTotalProgress();
    });

})( jQuery );
</script>
</block>